package com.nb.config;

import com.nb.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; // 导入 ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web MVC配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private JwtInterceptor jwtInterceptor;

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.access-path}")
    private String accessPath; // This value will now be /server/images/

    /**
     * 注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/error")
                // 放行静态资源访问路径 - 确保路径匹配与实际访问路径一致
                .excludePathPatterns("/server/images/**");
    }

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 所有接口
                .allowCredentials(true)  // 允许携带凭证
                .allowedOriginPatterns("*")  // 允许所有域名
                .allowedMethods("GET", "POST", "PUT","PATCH", "DELETE", "OPTIONS")  // 允许的请求方式
                .allowedHeaders("*")  // 允许所有请求头
                .maxAge(3600);  // 有效期1小时
    }

    /**
     * 添加静态资源处理器
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源映射，将URL路径映射到文件系统路径
        // 例如：访问 /server/images/user_1_xxx.jpg 会映射到 uploadPath/user_1_xxx.jpg
        registry.addResourceHandler(accessPath + "**") // Use the updated accessPath
                .addResourceLocations("file:" + uploadPath); // 使用 file: 前缀指定文件系统路径
    }
}